<template>
  <div>
    <el-form ref="myform" :model="formItem" :rules="rules" label-width="120px" size="mini">
      <el-tabs v-model="activeName">
        <el-tab-pane label="基本信息" name="first">
          <el-row :gutter="40">
            <el-col :span="12">
              <el-form-item label="合同名称" prop="name">
                <el-input v-model="formItem.name" placeholder="请输入合同名称" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="合同号" prop="code">
                <el-input v-model="formItem.code" placeholder="请输入合同号" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="合同类型" prop="type">
                <el-select v-model="formItem.type" clearable filterable remote placeholder="请选择合同类型" @change="typeChange">
                  <el-option v-for="(item) in typeList" :key="item.code" :label="item.text" :value="item.code" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="交货期限(天)" prop="deliveryDeadline">
                <el-input-number v-model="formItem.deliveryDeadline" :min="1" :max="999999" label="交货期限(天)" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="签订时间" prop="signingDate">
                <el-date-picker v-model="formItem.signingDate" type="datetime" format="yyyy-MM-dd" value-format="yyyy-MM-dd HH:mm:ss" placeholder="请选择签订时间" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="供货方名称" prop="manufacturerName">
                <el-autocomplete v-model="formItem.manufacturerName" style="width: 100%;" :fetch-suggestions="querySearch" placeholder="请输入供应商" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="合同金额" prop="amount">
                <el-input-number v-model="formItem.amount" :precision="2" :min="0" :max="99999999" label="合同金额(元)" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="发票" prop="bill">
                <el-input v-model="formItem.bill" placeholder="请输入发票" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="付款状况" prop="paymentStatus">
                <el-switch v-model="formItem.paymentStatus" active-color="#13ce66" inactive-color="#ff4949" active-text="已付款" inactive-text="未付款" />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="附件" prop="postCode">
                <el-upload
                  class="upload-demo"
                  :headers="headers"
                  :action="importUrl"
                  :on-success="handleSuccess"
                  :on-error="handleError"
                  :on-remove="handleRemove"
                  :multiple="true"
                  :show-file-list="true"
                  :file-list="formItem.attachment"
                  :http-request="uploadRequest"
                >
                  <el-button size="small" type="primary" icon="el-icon-upload2">上传</el-button>
                </el-upload>
              </el-form-item>
            </el-col>
          </el-row>
          <el-divider content-position="left">合同项信息</el-divider>
          <el-row>
            <div style="margin-bottom: 10px;">
              <el-button type="primary" size="mini" icon="el-icon-plus" @click="handleItemClick('1')">添加资产</el-button>
              <!-- 只有科技才能添加配件 -->
              <el-button v-if="belongs === 'kj' && formItem.type !== 'xh'" type="primary" size="mini" icon="el-icon-plus" @click="handleItemClick('2')">添加配件</el-button>
            </div>
            <el-table :loading="false" :data="formItem.items">
              <el-table-column v-for="column in insideColumns" :key="column.key" :label="column.title" :prop="column.key" :width="column.width" :sortable="column.sortable">
                <template slot-scope="scope">
                  <column-render :render="column.render" :row="scope.row" :column="column" />
                </template>
              </el-table-column>
              <el-table-column label="操作" align="center" width="230" class-name="small-padding fixed-width">
                <template slot-scope="{row}">
                  <el-button v-if="row.count !== row.acceptedCount" type="text" title="编辑" size="mini" icon="el-icon-edit" @click="edit(row)" />
                  <el-button v-if="row.count !== row.acceptedCount" type="text" title="删除" size="mini" icon="el-icon-delete" @click="remove(row)" />
                </template>
              </el-table-column>
            </el-table>
          </el-row>
        </el-tab-pane>
        <el-tab-pane label="其他信息" name="second">
          <el-row :gutter="40">
            <el-col :span="12">
              <el-form-item label="包装方式" prop="packing">
                <el-input v-model="formItem.packing" placeholder="请输入包装方式" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="运输方式" prop="transport">
                <el-input v-model="formItem.transport" placeholder="请输入运输方式" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="质量保障" prop="qualityAssurance">
                <el-input v-model="formItem.qualityAssurance" placeholder="请输入质量保障" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="到货地点" prop="arrivalAddress">
                <el-input v-model="formItem.arrivalAddress" placeholder="请输入到货地点" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="付款条件" prop="paymentTerms">
                <el-input v-model="formItem.paymentTerms" placeholder="请输入付款条件" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="备注" prop="remark">
                <el-input v-model="formItem.remark" placeholder="请输入备注" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="邮编" prop="postCode">
                <el-input v-model="formItem.postCode" placeholder="请输入邮编" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-tab-pane>
      </el-tabs>
    </el-form>
    <SelectDialog :show="itemSelect" title="添加合同项" width="55%" :append-to-body="true" @on-ok="selectItemOk" @on-cancel="selectItemCancel">
      <ItemEditForm v-if="itemSelect && selectType == '1'" ref="itemForm" :belongs="belongs" :obj="obj" :categories="categorieType" />
      <GoodsfileEditForm v-if="itemSelect && selectType == '2'" ref="itemForm" :belongs="belongs" :obj="obj" :categories="categorieType" />
    </SelectDialog>
  </div>
</template>

<script>
import { clone } from '@neu/biz-core/utils/utils'
import SelectDialog from '@neu/biz-core/components/SelectDialog'
import ItemEditForm from './itemEditForm'
import GoodsfileEditForm from './goodsfileEditForm'
import { CONTRACT_TYPE_LIST } from '@neu/dcam-ui/utils/constants'
import { getToken } from '@neu/biz-core/utils/auth'
import { deepClone } from '@neu/biz-core/utils'
import { list as getAllManufacturer } from '@neu/dcam-ui/api/manufacturer'
import {
  create,
  update,
  detail,
  uploadFileUrl
} from '@neu/dcam-ui/api/contract'
import axios from 'axios'

// 定义一个表单原始项
const formItem = {
  name: '',
  code: '',
  type: 'purchase',
  manufacturerName: '',
  postCode: '',
  deliveryDeadline: 90,
  signingDate: null,
  packing: '',
  transport: '',
  qualityAssurance: '',
  arrivalAddress: '',
  paymentTerms: '',
  remark: '',
  paymentStatus: false,
  whetherArrival: false,
  items: [],
  belongs: '',
  bill: '',
  /** 附件 */
  attachment: [],
  amount: ''
}
export default {
  name: 'ContractEditForm',
  components: {
    SelectDialog,
    ItemEditForm,
    GoodsfileEditForm
  },
  props: {
    // 根据id可判断是新建还是更新
    id: {
      required: false,
      type: Number,
      default: -1
    },
    belongs: {
      type: String,
      default: null,
      required: true
    }
  },
  data() {
    return {
      selectType: '',
      // 合同类型
      typeList: [...CONTRACT_TYPE_LIST],
      categorieType: '',
      anchorList: [ // 锚点列表
        { id: (this.id !== -1 ? 'editModule' : 'createModule') + '1', label: '基本信息' },
        { id: (this.id !== -1 ? 'editModule' : 'createModule') + '2', label: '其他信息' },
        { id: (this.id !== -1 ? 'editModule' : 'createModule') + '3', label: '合同详细' }
      ],
      itemSelect: false,
      // 编辑的表单内容
      formItem: clone(formItem),
      // 合同详细编辑
      obj: null,
      // 表单验证规则
      rules: {
        name: [
          { required: true, message: '合同名称不能为空', trigger: 'blur' },
          { max: 225, message: '长度不能超过225', trigger: 'blur' }
        ],
        code: [
          { required: true, message: '合同号不能为空', trigger: 'blur' },
          { max: 225, message: '长度不能超过225', trigger: 'blur' }
        ],
        type: [
          { required: true, message: '合同类型不能为空', trigger: 'blur' }
        ],
        manufacturerName: [
          // { required: true, message: '供货方名称不能为空', trigger: 'blur' },
          { max: 225, message: '长度不能超过225', trigger: 'blur' }
        ],
        paymentStatus: [
          // { required: true, message: '付款状态不能为空', trigger: 'blur' }
        ],
        deliveryDeadline: [
          // { required: true, message: '交货期限不能为空', trigger: 'blur' },
          {
            validator: function(rule, value, callback) {
              if (/^[0-9]*$/.test(value) === false) {
                callback(new Error('请输入正确的数字'))
              } else {
                callback()
              }
            },
            trigger: 'blur'
          }
        ],
        signingDate: [
          // { required: true, message: '签订时间不能为空', trigger: 'blur' }
        ],
        packing: [
          { max: 225, message: '长度不能超过225', trigger: 'blur' }
        ],
        arrivalAddress: [
          { max: 225, message: '长度不能超过225', trigger: 'blur' }
        ],
        paymentTerms: [
          { max: 225, message: '长度不能超过225', trigger: 'blur' }
        ],
        remark: [
          { max: 225, message: '长度不能超过225', trigger: 'blur' }
        ]
      },
      insideColumns: [
        { title: '分类名称', key: 'assetTypeName' },
        // { title: '产品名称', key: 'productName' },
        { title: '规格型号', key: 'standard' },
        { title: '金额', key: 'amount' },
        { title: '设备数量', key: 'count' },
        { title: '入库数量', key: 'acceptedCount' },
        { title: '描述', key: 'description' }
      ],
      modal: true,
      headers: {
        'Access-Control-Allow-Origin': '*',
        'Authentication': getToken()
      },
      importUrl: uploadFileUrl,
      activeName: 'first',
      manufacturers: []
    }
  },
  computed: {
    moduleType: function() {
      if (this.id !== -1) {
        return 'editModule'
      } else {
        return 'createModule'
      }
    }
  },
  watch: {
    // 监控id的变化，初始化表单数据
    id: function() {
      this.fetch()
    }
  },
  created() {
    this.fetch()
    getAllManufacturer().then(response => {
      this.manufacturers = response.data.map(m => {
        return {
          value: m.name
        }
      })
    })
  },
  methods: {
    // 初始化表单数据
    fetch() {
      if (this.id !== -1) {
        detail(this.id).then(response => {
          const data = response.data
          if (data.attachment) {
            const fileJoins = data.attachment.split('||')
            data.attachment = fileJoins.map(it => {
              const fsInfo = it.split('@@')
              return {
                fsId: fsInfo[0],
                name: fsInfo[1]
              }
            })
          } else {
            data.attachment = []
          }

          this.formItem = {
            ...data
          }
          // 标记初始化数据
          this.formItem.items.forEach(k => {
            k['init'] = true
          })
        })
      } else {
        this.formItem = clone(formItem)
      }
    },
    // 保存操作，返回promise，后续处理交由调用者处理
    save() {
      const updated = this.id !== -1
      return new Promise(resolve => {
        this.$refs.myform.validate((valid) => {
          if (valid) {
            // 添加所属
            this.formItem.belongs = this.belongs
            if (updated) {
              let whetherArrival = true
              // 去掉前端合同项ID
              this.formItem.items.forEach(element => {
                if (element.init !== true) {
                  element.id = null
                }
                if (element.count !== element.acceptedCount) {
                  whetherArrival = false
                }
                delete element.init
              })
              this.formItem.whetherArrival = whetherArrival
              const deepCloneForm = deepClone(this.formItem)
              // 将附件转为字符串存储
              if (deepCloneForm.attachment.length > 0) {
                deepCloneForm.attachment = deepCloneForm.attachment.map(it => it.fsId + '@@' + it.name).join('||')
              } else {
                deepCloneForm.attachment = ''
              }
              resolve(update(this.id, deepCloneForm))
            } else {
              // 去掉前端合同项ID
              this.formItem.items.forEach(element => {
                element.id = null
              })
              const deepCloneForm = deepClone(this.formItem)
              // 将附件转为字符串存储
              if (deepCloneForm.attachment.length > 0) {
                deepCloneForm.attachment = deepCloneForm.attachment.map(it => it.fsId + '@@' + it.name).join('||')
              } else {
                deepCloneForm.attachment = ''
              }
              resolve(create(deepCloneForm))
            }
          } else {
            resolve(false)
          }
        })
      })
    },
    reset() {
      this.formItem = clone(formItem)
    },
    handleItemClick(val) {
      this.selectType = val
      if (this.selectType === '1') {
        if (!this.formItem.type) {
          return this.$message({
            showClose: true,
            message: '请选择合同类型',
            type: 'error'
          })
        } else {
          if (this.formItem.type === 'xh') {
            this.categorieType = '3'
          } else {
            this.categorieType = ''
          }
          this.obj = null
          this.itemSelect = true
        }
      } else if (this.selectType === '2') {
        this.obj = null
        this.itemSelect = true
      }
    },
    selectItemOk() {
      // 直接调用表单实例的保存方法
      this.$refs.itemForm.save().then(response => {
        if (response === false) return
        const index = response.id
        const filterData = this.formItem.items.filter(ele => ele.id === index)
        if (filterData.length > 0) {
          this.formItem.items.forEach((element, inde) => {
            if (element.id === index) {
              for (var key in response) {
                this.formItem.items[inde][key] = response[key]
              }
            }
          })
        } else {
          const item = { id: this.genID(), ...response }
          this.formItem.items.push(item)
        }
        // 关闭对话框
        this.itemSelect = false
        this.$refs.itemForm.reset()
      })
    },
    selectItemCancel() {
      this.itemSelect = false
    },
    edit(row) {
      this.selectType = row.type
      this.obj = row
      this.itemSelect = true
    },
    remove(row) {
      this.formItem.items = this.formItem.items.filter(ele => ele.id !== row.id)
    },
    genID() {
      return Number(Math.random().toString().substr(3, 8) + Date.now()).toString(36)
    },
    typeChange() {
      this.formItem.items = []
    },
    /** 文件上传成功 */
    handleSuccess(response, file, fileList) {
      if (response.status === 'failure') {
        this.$message({
          showClose: true,
          message: response.data,
          type: 'error'
        })
      } else {
        const obj = {
          fsId: response.data.fsId,
          name: response.data.name
        }
        const fsIdArr = this.formItem.attachment.map(t => t.fsId)
        if (!fsIdArr.includes(obj.fsId)) {
          this.formItem.attachment.push(obj)
        } else {
          fileList.pop()
        }
      }
    },
    /** 文件上传失败 */
    handleError(err, file, fileList) {
      console.log(err)
    },
    /** 文件移除 */
    handleRemove(file, fileList) {
      this.formItem.attachment.splice(this.formItem.attachment.indexOf(file), 1)
    },
    querySearch(queryString, cb) {
      const manufacturers = this.manufacturers
      const results = queryString ? manufacturers.filter(this.createFilter(queryString)) : manufacturers
      cb(results)
    },
    createFilter(queryString) {
      return (m) => {
        return (m.value.toLowerCase().indexOf(queryString.toLowerCase()) > -1)
      }
    },
    uploadRequest(param) {
      const that = this
      const fileObj = param.file
      const formData = new FormData()
      formData.append('file', fileObj)
      axios.post(this.importUrl, formData, { headers: this.headers }).then((response) => {
        const data = response.data.data
        const obj = {
          fsId: data.fsId,
          name: data.name
        }
        const fsIdArr = that.formItem.attachment.map(t => t.fsId)
        that.formItem.attachment.push(obj)
        if (fsIdArr.includes(obj.fsId)) {
          that.formItem.attachment.pop()
        }
      })
    }
  }
}
</script>
